<?php

class Solicitacao extends DataMapper {

	var $error_prefix = '<div class="alert alert-danger" role="alert">';
    var $error_suffix = '</div>';
	
    var $table = 'solicitacoes';
	

    function __construct($id = NULL)
    {
        parent::__construct($id);
    }
	public function pluck ( $a, $prop )	{
		$out = array();

		for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
			$out[] = $a[$i][$prop];
		}

		return $out;
	}
	public function historicosolicitacoes(){
		
		$table = "solicitacoes";
		$columns = array(
		
			array( 'db' => 'solicitacoes.id','dt' => 0 ),
			array( 'db' => 'date_format(solicitacoes.dt_cadastro, "%d/%m/%Y %T") as dt_cadastro','dt' => 1 ),
			array( 'db' => 'solicitacoes.nomesolicitante','dt' => 2 ),
			array( 'db' => 'solicitacoes.ramal','dt' => 3 ),
			array( 'db' => 'solicitacoes.email','dt' => 4 ),
			array( 'db' => 'solicitacoes.justificativa','dt' => 5 ),
			array( 'db' => 'usuarios.nome_completo','dt' => 6 ),
			array( 'db' => 'solicitacoes.solucao','dt' => 7 )
		);
		
		$columnsaux = array(
		
			array( 'db' => 'solicitacoes.id','dt' => 0 ),
			array( 'db' => 'solicitacoes.dt_cadastro','dt' => 1 ),
			array( 'db' => 'solicitacoes.nomesolicitante','dt' => 2 ),
			array( 'db' => 'solicitacoes.ramal','dt' => 3 ),
			array( 'db' => 'solicitacoes.email','dt' => 4 ),
			array( 'db' => 'solicitacoes.justificativa','dt' => 5 ),
			array( 'db' => 'usuarios.nome_completo','dt' => 6 ),
			array( 'db' => 'solicitacoes.solucao','dt' => 7 )
		);
		//**********************************************************************
		// LIMITE
		//**********************************************************************
		$sLimit = "";
		if ( isset( $_GET['start'] ) && $_GET['length'] != '-1' )
		{
			$sLimit = "LIMIT ".intval( $_GET['start'] ).", ".intval( $_GET['length'] );
		}
		
		
		//**********************************************************************
		// ORDENAÇÃO
		//**********************************************************************
		$order = '';
	
		if ( isset($_GET['order']) && count($_GET['order']) ) {
			$orderBy = array();
			$dtColumns = $this->pluck( $columnsaux, 'dt' );

			for ( $i=0, $ien=count($_GET['order']) ; $i<$ien ; $i++ ) {
				// Convert the column index into the column data property
				$columnIdx = intval($_GET['order'][$i]['column']);
				$requestColumn = $_GET['columns'][$columnIdx];

				$columnIdx = array_search( $requestColumn['data'], $dtColumns );
				$column = $columnsaux[ $columnIdx ];

				if ( $requestColumn['orderable'] == 'true' ) {
					$dir = $_GET['order'][$i]['dir'] === 'asc' ?
						'ASC' :
						'DESC';

					$orderBy[] = ''.$column['db'].' '.$dir;
				}
			}

			$order = 'ORDER BY '.implode(', ', $orderBy);
		}
		
		$globalSearch = array();
		$columnSearch = array();
		$dtColumns = $this->pluck( $columnsaux, 'dt' );


		if ( isset($_GET['search']) && $_GET['search']['value'] != '' ) {
			$str = $_GET['search']['value'];

			for ( $i=0, $ien=count($_GET['columns']) ; $i<$ien ; $i++ ) {
				$requestColumn = $_GET['columns'][$i];
				$columnIdx = array_search( $requestColumn['data'], $dtColumns );
				$column = $columnsaux[ $columnIdx ];

				if ( $requestColumn['searchable'] == 'true' ) {
					//$binding = '%'.$str.'%';
					if($column['db'] == 'solicitacoes.dt_cadastro'){$globalSearch[] = " ".$column['db']." LIKE '%".brToUsaHora($str)."%'";}else{
						$globalSearch[] = " ".$column['db']." LIKE '%".$str."%'";
					}
				}
			}
		}


		
		//**********************************************************************
		// WHERE
		//**********************************************************************
		// Individual column filtering
		
		for ( $i=0, $ien=count($_GET['columns']) ; $i<$ien ; $i++ ) {
			$requestColumn = $_GET['columns'][$i];
			$columnIdx = array_search( $requestColumn['data'], $dtColumns );
			$column = $columnsaux[ $columnIdx ];

			$str = $requestColumn['search']['value'];

			if ( $requestColumn['searchable'] == 'true' && $str != '' ) {
				//$binding = '%'.$str.'%';
				$columnSearch[] = " ".$column['db']." LIKE '%".$str."%'";
			}
		}

		// Combine the filters into a single string
		$where = '';

		if ( count( $globalSearch ) ) {
			$where = '('.implode(' OR ', $globalSearch).')';
				$status = " `solicitacoes`.`status` = '0' AND `solicitacoes`.`usuario_id` IS NOT NULL";
				$where .= " AND ".$status;
			
		}

		if ( count( $columnSearch ) ) {
			$where = $where === '' ? 
				implode(' AND ', $columnSearch) :
				$where .' AND '. implode(' AND ', $columnSearch);
		}

		
		if ( $where !== '' ) {
			$where = 'WHERE '.$where;
		}else{
				$status = " `solicitacoes`.`status` = '0' AND `solicitacoes`.`usuario_id` IS NOT NULL";
				$where = 'WHERE '.$status;
					
		}
		

		

		
        $result = $this->db->query("
		SELECT 
		".implode(", ", $this->pluck($columns, 'db'))." 
		FROM $table 
		LEFT JOIN usuarios on usuarios.id = solicitacoes.usuario_id 
		$where 
		$order  
		$sLimit	"
		);
		
		/*echo "
		SELECT 
		".implode(", ", $this->pluck($columns, 'db'))." 
		FROM $table 
		LEFT JOIN usuarios on usuarios.id = solicitacoes.usuario_id 
		$where 
		$order  
		$sLimit	";
		*/
	
	
		$s1 = new Solicitacao();
		$s1->_process_query($result);
		
		$result = $this->db->query("SELECT FOUND_ROWS() as recordsTotal");
		
		$s2 = new Solicitacao();
		
		$s2->_process_query($result);
		$recordsTotal = '';
		
		foreach($s2 as $u){
			$recordsTotal = $u->recordsTotal;
		}
		
		
		$result = $this->db->query("SELECT COUNT(solicitacoes.id) as recordsFiltered  FROM solicitacoes");
		
		$s3 = new Solicitacao();
		
		$recordsFiltered = '';
		$s3->_process_query($result);
		foreach($s3 as $u){
			$recordsFiltered = $u->recordsFiltered;
		}
		
		$dados = array();
		$vetor = array();
		
		
		$vetor["draws"] = $_GET['draw'];
		$vetor["recordsTotal"] = $recordsTotal;
		$vetor["recordsFiltered"] = $recordsFiltered;
		

		
		foreach($s1 as $u){
			$aux = array();
		

			$aux[] = $u->id;
			$aux[] = $u->dt_cadastro;
			$aux[] = $u->nomesolicitante;
			$aux[] = $u->ramal;
			$aux[] = $u->email;
			$aux[] = $u->justificativa;
			$aux[] = $u->nome_completo;
			$aux[] = $u->solucao;
			
			array_push($dados,$aux);
		}
		
		$vetor["data"] = $dados;
		
		
		echo json_encode($vetor);
		
		
	}
}

/* End of file local.php */
/* Location: ./application/models/local.php */
